package nl.hanze.designpatterns.DAO.impl.file.crypted;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import nl.hanze.designpatterns.DAO.LoginCredentialDAO;
import nl.hanze.designpatterns.domain.LoginCredential;
import nl.hanze.designpatterns.io.CryptedInputStream;

public class LoginCredentialsDAOImpl implements LoginCredentialDAO {
	
	public LoginCredentialsDAOImpl() {
		
	}

	@Override
	public boolean isValid(LoginCredential loginCredential) {
		try {
			byte[] bytes = loginCredential.getPassword().getBytes("UTF-8");
			byte[] hashKey =  MessageDigest.getInstance("MD5").digest(bytes);
			
			return this.getCredentials(hashKey).equals(loginCredential.toString());
			
		} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}
	
	private String getCredentials(byte[] hashKey){
		try {
			FileInputStream input = new FileInputStream(LoginCredCreator.CRED_PATH);
			CryptedInputStream inputStream = new CryptedInputStream(input, hashKey);
			String credentials = new String(inputStream.completeReadOut(), "UTF-8");
			inputStream.close();
			
			return credentials;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return null;
	}

}
